﻿namespace DCHealthCheck {

    #region Usings
    using DCHealthCheck.DomainModel;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Management;
    using System.Text; 
    #endregion

    public class InstalledProductBuilder {

        #region Members
        private readonly InstalledProduct InstalledProduct;

        private readonly ManagementObject WmiObject; 
        #endregion

        #region Constructors
        private InstalledProductBuilder() {
        }

        public InstalledProductBuilder(InstalledProduct installedProduct, ManagementObject wmiObject)
            : this() {
            if (installedProduct == null) {
                throw new ArgumentNullException("installedProduct");
            }
            if (wmiObject == null) {
                throw new ArgumentNullException("wmiObject");
            }

            this.InstalledProduct = installedProduct;
            this.WmiObject = wmiObject;
        } 
        #endregion

        #region Methods
        public InstalledProduct GetInstalledProduct() {

            if (WmiObject["Description"] != null) this.InstalledProduct.Description = WmiObject["Description"].ToString();
            if (WmiObject["Name"] != null) this.InstalledProduct.Name = WmiObject["Name"].ToString();

            if (WmiObject["IdentifyingNumber"] != null) {
                this.InstalledProduct.IdentifyingNumber = Guid.Parse(WmiObject["IdentifyingNumber"].ToString());
            }

            if (WmiObject["InstallDate"] != null) {
                DateTime installDate = DateTime.MinValue;
                if (DateTime.TryParseExact(WmiObject["InstallDate"].ToString().Substring(0, 8), "yyyyMMdd", CultureInfo.CurrentCulture.DateTimeFormat, DateTimeStyles.None, out installDate)) {
                    this.InstalledProduct.InstallDate = installDate;
                }
            }

            if (WmiObject["Vendor"] != null) this.InstalledProduct.Vendor = WmiObject["Vendor"].ToString();
            if (WmiObject["Version"] != null) this.InstalledProduct.Version = WmiObject["Version"].ToString();

            return this.InstalledProduct;
        } 
        #endregion

    }
}
